package com.time.admin.domain.service.impl;

import com.alibaba.nacos.api.NacosFactory;
import com.alibaba.nacos.api.config.ConfigService;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.time.admin.domain.constants.AdminConstant;
import com.time.admin.domain.constants.ExceptionCode;
import com.time.admin.domain.converter.SettingBOConverter;
import com.time.admin.domain.entity.SettingBO;
import com.time.admin.domain.exception.NotFoundDomainException;
import com.time.admin.domain.service.AdminSettingDomainService;
import com.time.admin.domain.utils.YamlSerializerUtil;
import com.time.admin.common.config.BackupProperties;
import com.time.admin.common.config.EmailProperties;
import com.time.admin.common.config.WebsiteProperties;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.Arrays;
import java.util.stream.Collectors;

/**
 * 系统设置管理领域服务层实现类
 *
 * @author: HuangQi
 * @date: Created in 16:14 2025/11/11
 * @description: 系统设置管理领域服务层实现
 */
@Slf4j
@Service("adminSettingDomainServiceImpl")
public class AdminSettingDomainServiceImpl implements AdminSettingDomainService {

    @Resource
    private BackupProperties backupProperties;

    @Resource
    private EmailProperties emailProperties;

    @Resource
    private WebsiteProperties websiteProperties;

    @Resource
    private SettingBOConverter settingBOConverter;

    @Override
    public Boolean update(SettingBO settingBO, String name) {
        if (log.isInfoEnabled()) {
            log.info("AdminSettingDomainServiceImpl.update.bo:{}, name:{}", settingBO, name);
        }

        // 更新配置类
        Object updatedBean;
        if (StringUtils.equals(name, AdminConstant.WEBSITE_STR)) {
            settingBOConverter.mapWebsite(settingBO, websiteProperties);
            updatedBean = websiteProperties;
        } else if (StringUtils.equals(name, AdminConstant.EMAIL_STR)) {
            settingBOConverter.mapEmail(settingBO, emailProperties);
            updatedBean = emailProperties;
        } else if (StringUtils.equals(name, AdminConstant.BACKUP_STR)) {
            settingBOConverter.mapBackup(settingBO, backupProperties);
            updatedBean = backupProperties;
        } else {
            throw new NotFoundDomainException(ExceptionCode.CONFIG_NOT_EXISTS, "该配置项不存在");
        }

        // 统一更新 Nacos
        try {
            String serverAddr = "192.168.102.69:8848";
            ConfigService configService = NacosFactory.createConfigService(serverAddr);
            String dataId = "blog-admin-config.yml";
            String group = "DEFAULT_GROUP";
            String content = YamlSerializerUtil.toYaml(updatedBean);
            return configService.publishConfig(dataId, group, content);
        } catch (Exception e) {
            throw new RuntimeException("更新 Nacos 配置失败", e);
        }
    }

    @Override
    public SettingBO querySetting(String name) {
        if (log.isInfoEnabled()) {
            log.info("AdminSettingDomainServiceImpl.querySetting.name:{}", name);
        }

        // 获取配置信息
        SettingBO settingBO = new SettingBO();
        if (StringUtils.equals(name, AdminConstant.WEBSITE_STR)) {
            // 获取网站配置信息
            settingBO.setWebsite(SettingBO.WebsiteSetting.builder()
                    .siteName(websiteProperties.getSiteName())
                    .description(websiteProperties.getDescription())
                    .keywords(websiteProperties.getKeywords())
                    .logoUrl(websiteProperties.getLogoUrl())
                    .faviconUrl(websiteProperties.getFaviconUrl())
                    .icp(websiteProperties.getIcp())
                    .copyright(websiteProperties.getCopyright())
                    .contactEmail(websiteProperties.getContactEmail())
                    .build());
        } else if (StringUtils.equals(name, AdminConstant.EMAIL_STR)) {
            settingBO.setEmail(
                    // 获取邮件配置信息
                    SettingBO.EmailSetting.builder()
                            .host(emailProperties.getSmtp().getHost())
                            .port(emailProperties.getSmtp().getPort())
                            .defaultFrom(emailProperties.getDefaultFrom())
                            .fromName(emailProperties.getSmtp().getFromName())
                            .enabled(emailProperties.getEnabled())
                            .username(emailProperties.getSmtp().getUsername())
                            .password(emailProperties.getSmtp().getPassword())
                            .sslEnabled(emailProperties.getSmtp().getSslEnabled())
                            .build());
        } else if (StringUtils.equals(name, AdminConstant.BACKUP_STR)) {
            settingBO.setBackup(
                    // 获取备份配置信息
                    SettingBO.BackupSetting.builder()
                            .enabled(backupProperties.getEnabled())
                            .frequency(backupProperties.getFrequency().name)
                            .keepCount(backupProperties.getKeepCount())
                            .contents(Arrays.stream(BackupProperties.Content.values())
                                    .map(BackupProperties.Content::getName)
                                    .collect(Collectors.toList()))
                            .build());
        } else {
            throw new NotFoundDomainException(ExceptionCode.CONFIG_NOT_EXISTS, "该配置项不存在");
        }

        // 返回结果
        return settingBO;
    }
}
